//
//  MinePersonalInfotmationViewController.swift
//  House
//
//  Created by 吕品 on 16/7/5.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
import MBProgressHUD
class MinePersonalInfotmationViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var tableView = UITableView()
    var naviBar = BaseTitleNavigationBar()
    
    let titleArray = [["头像", "昵称"], ["手机号"], ["修改密码"]]
    let placeArray = [["",UserInfoManager.shared().nickName ?? "请填写昵称"], [UserInfoManager.shared().phoneNumber], [""]]

    override func viewWillAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableView.reloadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        tabbarHidden = true
        naviBar = BaseTitleNavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 64), withTitleStr: "我的个人信息")
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(back(tap:)))
        
        naviBar.leftView.addGestureRecognizer(tap)
        view.addSubview(naviBar)
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 64, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 64), style: .grouped)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        // Do any additional setup after loading the view.
        tableView.register(MinePersonalInfoTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(MinePersonalInfoTableViewCell.self))
        tableView.tableFooterView?.backgroundColor = UIColor.groupTableViewBackground
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeArray[section].count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(MinePersonalInfoTableViewCell.self)) as! MinePersonalInfoTableViewCell

        cell.mixView.label.text = titleArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        cell.mixView.showTextField = true
        cell.mixView.textField.placeholder = placeArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        cell.mixView.textField.isEnabled = false
        if (indexPath as NSIndexPath).section == 0 {
            if (indexPath as NSIndexPath).row == 0 {
                cell.mixView.showTextField = false
                NetRequest.downloadImage(withUrl: PHPHeader.manager().headImageReadPHP, imageView: cell.mixView.imageView, placeHolder: UIImage.init(named: "MineBackButtonImage"))
                cell.mixView.imageView.contentMode = .scaleAspectFit
                cell.mixView.imageView.layer.masksToBounds = true
                cell.mixView.imageView.layer.cornerRadius = 30
                cell.mixView.imageView.contentMode = .scaleAspectFill
            }
        }
        cell.selectionStyle = .none
        return cell

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath as NSIndexPath).section == 0 {
            if (indexPath as NSIndexPath).row == 0 {
                return 80
            }
        }
        return 50
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch (indexPath as NSIndexPath).section {
        case 0:
            if (indexPath as NSIndexPath).row == 0{//头像
                let imageVC = UIImagePickerController.init()
                imageVC.delegate = self
                let alertVC = UIAlertController.init(title: nil, message: "更改头像", preferredStyle: .actionSheet)

                let cameraAction = UIAlertAction.init(title: "拍照", style: .default, handler: { (action) in
                    imageVC.sourceType = .camera
                    self.present(imageVC, animated: true, completion: {

                    })
                })
                let photoAction = UIAlertAction.init(title: "从相册获取", style: .default, handler: { (action) in
                    imageVC.sourceType = .photoLibrary
                    self.present(imageVC, animated: true, completion: {

                    })
                })

                let cancelAction = UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in

                })

                alertVC.addAction(cameraAction)
                alertVC.addAction(photoAction)
                alertVC.addAction(cancelAction)
                modalPresentationStyle = .popover
                self.present(alertVC, animated: true, completion: {

                })

            } else {//昵称
                let nickNameVC = MineNickNameViewController()
                self.navigationController!.pushViewController(nickNameVC, animated: true)
            }
            break
        case 1://电话
            let phoneVC = MinePhoneNumberChangeViewController()
            self.navigationController!.pushViewController(phoneVC, animated: true)
            break
        case 2://密码
            let passWordVC = MinePasswordChangeViewController()
            self.navigationController!.pushViewController(passWordVC, animated: true)

            break
        default:
            break
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        self.dismiss(animated: true) {
            
        }
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.label.text = "正在上传"
        hud.mode = .determinateHorizontalBar
        let uid = UserInfoManager.shared().uid
        var str = ""
        if UIImagePNGRepresentation(image) != nil {
            str = ".png"
        } else {
            str = ".jpg"
        }
        NetRequest.upLoad(image, withUrl: PHPHeader.manager().headImageUploadPHP, withParameters: ["id": uid!, "dir": "fd", "target_file": "headImage" + uid! + str], progress: { (progress) in
            hud.progress = (Float)((progress?.completedUnitCount)! / (progress?.totalUnitCount)!)
            print(hud.progress)
            }, success: { (task, responseObj) in
                print(responseObj)
                if responseObj is NSDictionary {
                    let response = responseObj as! NSDictionary
                    if (response["flg"] as! NSNumber).description == "1" {
                        self.hide(withTitle: "上传成功")
                        self.tableView.reloadData()
                        let _ = self.navigationController!.popToRootViewController(animated: true)
                    } else {
                        self.hide(withTitle: "上传失败!")
                    }
                }

            }) { (task, error) in
                print(error)
                self.hide(withTitle: "上传失败")
        }

    }
    
    @objc func back(tap: UITapGestureRecognizer) -> Void {
        self.navigationController!.popViewController(animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
